package org.szrcb.temu.SalesManage.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.szrcb.temu.SalesManage.DTO.AfterSalesDTO;
import org.szrcb.temu.SalesManage.Vo.ResultVO;
import org.szrcb.temu.SalesManage.po.AfterSalesPo;
import org.szrcb.temu.SalesManage.po.AfterSalesResult;
import org.szrcb.temu.SalesManage.po.WarehouseResult;
import org.szrcb.temu.SalesManage.po.subOrder;
import org.szrcb.temu.SalesManage.pojo.Deduct;
import org.szrcb.temu.SalesManage.pojo.Warehouse;
import org.szrcb.temu.SalesManage.req.AfterSalesReq;
import org.szrcb.temu.SalesManage.req.WarehouserReq;
import org.szrcb.temu.SalesManage.service.MallInfoService;
import org.szrcb.temu.SalesManage.service.UserInfoService;
import org.szrcb.temu.SalesManage.service.WarehouseService;
import org.szrcb.temu.SalesManage.utils.ResultVOUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.util.*;

@RestController
public class AfterSalesController {
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private WarehouseService warehouseService;

    @PostMapping("queryAfterSalesList")
    public ResultVO<List<Deduct>> queryDeductList(@RequestHeader("access_token") String accessToken, @RequestParam("mallId") String mallId) {
        String cookie = "";
        if (accessToken != null && !"".equals(accessToken.trim())) {
            cookie = userInfoService.queryUserCookie(accessToken);
            if ("".equals(cookie.trim())) {
                return ResultVOUtil.error(1, "token不正确,请先登录Temu后台");
            }
        }

        AfterSalesReq afterSalesReq = new AfterSalesReq();
        afterSalesReq.setPageNo(1);
        afterSalesReq.setPageSize(100);
        afterSalesReq.setBizDrType(101);

        List<AfterSalesPo> afterSalesPos = new ArrayList<>();
        afterSalesPos = formartAfterSalesPos(afterSalesPos, "美国", cookie, mallId, afterSalesReq);

        afterSalesReq.setPageNo(1);
        afterSalesReq.setBizDrType(202);
        afterSalesPos = formartAfterSalesPos(afterSalesPos, "欧洲", cookie, mallId, afterSalesReq);

        afterSalesReq.setPageNo(1);
        afterSalesReq.setBizDrType(102);
        afterSalesPos = formartAfterSalesPos(afterSalesPos, "其他", cookie, mallId, afterSalesReq);
        //得到所有数据的list

        Map<String, Integer> countMap = new HashMap<>();
        List<String> productSkuIds = new ArrayList<>();
        List<AfterSalesDTO> dtoList = new ArrayList<>();

        if (afterSalesPos != null && afterSalesPos.size() > 0) {
            for (AfterSalesPo afterSalesPo : afterSalesPos) {
                productSkuIds.add(afterSalesPo.getProductSkuId().get(0));

                String key = afterSalesPo.getProductSkuId().get(0) + "_" + String.valueOf(afterSalesPo.getPunishRatio());
                countMap.put(key, countMap.getOrDefault(key, 0) + 1);
            }
            List<Warehouse> warehouseList = warehouseService.queryMallListByProductId(productSkuIds);

            HashMap<String, Double> supplierPriceMap = new HashMap<>();
            HashMap<String, Double> buyingPriceMap = new HashMap<>();
            HashMap<String, String> picUrlMap = new HashMap<>();
            if (warehouseList != null && warehouseList.size() > 0) {
                warehouseList.forEach(warehouse -> {
                    supplierPriceMap.put(warehouse.getProductSkuId(), warehouse.getSupplierPrice());
                    buyingPriceMap.put(warehouse.getProductSkuId(), warehouse.getBuyingPrice());
                    picUrlMap.put(warehouse.getProductSkuId(), warehouse.getProductSkcPicture());
                });
            }

            // 通过keySet()方法获取所有键
            Set<String> keys = countMap.keySet();
            // 遍历键集合并获取值
            for (String key : keys) {
                String[] split = key.trim().split("_");
                String productSkuId = split[0];
                AfterSalesDTO afterSalesDTO = new AfterSalesDTO();
                afterSalesDTO.setProductSkuId(productSkuId);
                afterSalesDTO.setPunishRatio(Double.valueOf(split[1]));
                afterSalesDTO.setCount(countMap.get(key));

                afterSalesDTO.setBuyingPrice(buyingPriceMap.get(productSkuId) == null ? 0 : buyingPriceMap.get(productSkuId));
                afterSalesDTO.setSupplierPrice(supplierPriceMap.get(productSkuId) == null ? 0 : supplierPriceMap.get(productSkuId));
                afterSalesDTO.setProductSkcPicture(picUrlMap.get(productSkuId) == null ? "" : picUrlMap.get(productSkuId));

                afterSalesDTO.setTotalSupplierPrice(afterSalesDTO.getSupplierPrice() * afterSalesDTO.getPunishRatio() * afterSalesDTO.getCount());
                afterSalesDTO.setDeductBuyingPrice(afterSalesDTO.getBuyingPrice() * afterSalesDTO.getCount());
                dtoList.add(afterSalesDTO);
            }
        }
        return ResultVOUtil.success(dtoList);
    }

    private List<AfterSalesPo> formartAfterSalesPos(List<AfterSalesPo> list, String bizDrType, String cookie, String mallId, AfterSalesReq afterSalesReq) {
        AfterSalesResult afterSalesResult = getAfterSalesResult(cookie, mallId, afterSalesReq);
        Integer total = afterSalesResult.getTotal();

        List<AfterSalesPo> afterSalesPos = afterSalesResult.getList();
        if (afterSalesPos != null && afterSalesPos.size() > 0) {
//            afterSalesPos.forEach(afterSalesPo -> {
//                afterSalesPo.setBizDrType(bizDrType);
//            });
            list.addAll(afterSalesPos);
        }

        //计算页数，查询
        int totalPages = (int) Math.ceil((double) total / afterSalesReq.getPageSize()); // 总页数，使用Math.ceil向上取整
        if (totalPages > 1) {
            for (int i = afterSalesReq.getPageNo() + 1; i <= totalPages; i++) {
                afterSalesReq.setPageNo(i);
                afterSalesResult = getAfterSalesResult(cookie, mallId, afterSalesReq);
                afterSalesPos = afterSalesResult.getList();
                if (afterSalesPos != null && afterSalesPos.size() > 0) {
//                    afterSalesPos.forEach(afterSalesPo -> {
//                        afterSalesPo.setBizDrType(bizDrType);
//                    });
                    list.addAll(afterSalesPos);
                }
            }
        }
        return list;
    }

    private AfterSalesResult getAfterSalesResult(String cookie, String mallId, AfterSalesReq afterSalesReq) {
        JSONObject afterSalesJson = null;
        boolean afterSalesBoolean = false;
        //循环请求数据
        while (!afterSalesBoolean) {
            afterSalesJson = getAfterSalesJson("https://agentseller.temu.com/mms/api/appalachian/afs/queryPageV2", cookie, mallId, afterSalesReq);
            String errorCode = afterSalesJson.getObject("errorCode", String.class);
            if ("40001".equals(errorCode)) {
                throw new RuntimeException("登录过期，请重新登录");
            }
            if ("1000000".equals(errorCode)) {
                afterSalesBoolean = afterSalesJson.getObject("success", boolean.class);
            }
        }
        return afterSalesJson.getObject("result", AfterSalesResult.class);
    }


    private JSONObject getAfterSalesJson(String httpUrl, String cookie, String mallId, AfterSalesReq afterSalesReq) {
        StringBuilder content = new StringBuilder();
        HttpURLConnection conn = null;
        BufferedReader br = null;
        try {
            URL url = new URL(httpUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Origin", "https://agentseller.temu.com");
            conn.setRequestProperty("cookie", cookie);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setRequestProperty("MallId", mallId);
            conn.setDoOutput(true);

            String warehouseReqJson = JSON.toJSONString(afterSalesReq);

            try (OutputStream os = conn.getOutputStream()) {
                os.write(warehouseReqJson.getBytes());
            }

            conn.connect();

            br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;

            while ((inputLine = br.readLine()) != null) {
                content.append(inputLine);
            }
            br.close();
            conn.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
                conn.disconnect();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return JSONObject.parseObject(content.toString());
    }
}
